package cn.tedu.cat.controller;

import cn.tedu.cat.entity.User;
import cn.tedu.cat.entity.Baobei;
import cn.tedu.cat.mapper.BaobeiMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class BaobeiController {
    @Autowired(required = false)
    BaobeiMapper mapper;
    @RequestMapping("/baobei/insert")
    public int insert(Baobei baobei, MultipartFile picFile, HttpSession session) throws IOException {
        //得到当前登录的用户对象
        User u = (User) session.getAttribute("u");
        if (u==null){
            return 0;//未登录
        }
        //得到原始文件名
        String fileName = picFile.getOriginalFilename();
        //得到后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名
        fileName = UUID.randomUUID()+suffix;
        //准备文件夹
        String dirPath = "D:/upload";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){ //判断如果没有文件夹
            dirFile.mkdirs(); //创建文件夹
        }
        //得到文件的完整路径
        String filePath = dirPath+"/"+fileName;
        //保存文件
        picFile.transferTo(new File(filePath));
        // url,author,created,userId      url= /xxxx.jpg
        baobei.setUrl("/"+fileName);
        //把当前登录的用户信息保存在weibo对象中

//        System.out.println("weibo="+weibo);
        mapper.insert(baobei);
        return 1;//表示发布成功
    }

    @RequestMapping("/baobei/select1")
    public List<Baobei> select(){
        return mapper.select();
    }
    @RequestMapping("/baobei/select2")
    public List<Baobei> select2(){
        return mapper.select2();
    }
    @RequestMapping("/baobei/select3")
    public List<Baobei> select3(){
        return mapper.select3();
    }
    @RequestMapping("/baobei/select4")
    public List<Baobei> select4(){
        return mapper.select4();
    }
    @RequestMapping("/baobei/select5")
    public List<Baobei> select5(){
        return mapper.select5();
    }
    @RequestMapping("/baobei/select6")
    public List<Baobei> select6(){
        return mapper.select6();
    }

    @RequestMapping("/baobei/selectById")
    public Baobei selectById(int id){
        return mapper.selectById(id);
    }

}
